﻿using SearchStarPlus.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;

namespace SearchStarPlus.Controllers
{
    public class KeywordExclusionController : Controller
    {
        //
        // GET: /KeywordExclusion/

        public ActionResult Index()
        {
            return View();
        }

        private string apiUrl = "";
        HttpClient client = new HttpClient();

        public KeywordExclusionController(string baseUrl, string apiUrl)
        {
            this.apiUrl = apiUrl;
            this.client.BaseAddress = new Uri(baseUrl);
            this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public List<KeywordExclusion> Get()
        {
            HttpResponseMessage response = client.GetAsync(this.apiUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var words = response.Content.ReadAsAsync<IEnumerable<KeywordExclusion>>().Result;
                return words.ToList();
            }
            else
            {
                return null;
            }
        }

        public string PostInsert(KeywordExclusion newWord)
        {
            HttpResponseMessage response = client.PostAsJsonAsync(apiUrl, newWord).Result;
            if (response.IsSuccessStatusCode)
            {
                return string.Format("Category{0} inserted successfully", newWord.Word);
            }
            else
            {
                return string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }

        public string PutUpdate(KeywordExclusion update)
        {
            HttpResponseMessage response = client.PutAsJsonAsync<KeywordExclusion>(this.apiUrl + update.ExclusionId, update).Result;
            if (response.IsSuccessStatusCode)
            {
                return string.Format("Category{0} updated successfully", update.ExclusionId);
            }
            else
            {
                return string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }

        public string Delete(int exclusionId)
        {
            HttpResponseMessage response = client.DeleteAsync(this.apiUrl + exclusionId).Result;
            if (response.IsSuccessStatusCode)
            {
                return string.Format("Category{0} deleted successfully", exclusionId);
            }
            else
            {
                return string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }
    }
}
